<template>
  <view class="uni-container">
    <uni-popup ref="message" type="message">
				<uni-popup-message type="error" :message="messageText" :duration="1500"></uni-popup-message>
		</uni-popup>
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="sort_id" label="排序ID">
        <uni-easyinput placeholder="值越大越往后" type="number" v-model="formData.sort_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="school_id" label="所属学校" required>
        <uni-data-picker v-model="formData.school_id" collection="admin-school-list" field="school_name as text, _id as value"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="nav_path" label="广告链接" required>
        <uni-easyinput placeholder="点击后到达的广告目的地" v-model="formData.nav_path" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="desc_info" label="广告描述">
        <uni-easyinput type="textarea" placeholder="最多200个字" v-model="formData.desc_info" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="carousel_icon" label="广告图片">
        <uni-file-picker ref="files" @select="(e)=>fileList=e" @delete="()=>fileList==null" :auto-upload="false" file-mediatype="image" file-extname="jpg,png" :limit="1" return-type="array" v-model="formData.carousel_icon"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="show_status" label="显示或关闭">
        <switch style="transform: scale(0.8);" @change="binddata('show_status', $event.detail.value)" :checked="formData.show_status"></switch>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/food-home-carousel.js';
  const adminFilesMG = uniCloud.importObject('admin-files-manage',{
      customUI:true
  }) 

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'food-home-carousel';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "sort_id": 0,
        "school_id": "",
        "nav_path": "",
        "desc_info": "",
        "carousel_icon": [],
        "show_status": true
      }
      return {
        formData,
        formOptions: {},
        fileList:null,
        messageText:`广告图片必须上传`,
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then(async (res) => {

          if(res.carousel_icon.length===0&&this.fileList==null){
              return this.$refs.message.open()
          }

          if(this.fileList!=null){
        
            await adminFilesMG.removeFile({
                table:dbCollectionName,
                id:[this.formDataId],
                field:`carousel_icon`
              });

              res.carousel_icon= await this.$refs.files.upload();
            }

          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("sort_id,school_id,nav_path,desc_info,carousel_icon,show_status").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
